package com.ihrm.shiro.realm;

import com.ihrm.domain.system.User;
import com.ihrm.system.service.UserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm实现登录认证和授权
 * @auther chongxiongwei
 * @create 2020-06-09-23:11
 */
public class CustomRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    //
    public void setName(String name){
        super.setName("customRealm");
    }

    @Autowired
    private UserService userService;
    /**
     * 权限授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录认证
     * @param authenticationToken   upToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)authenticationToken;
        // 1.从传入的token中获取username password
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());
        logger.info("********AuthenticationInfo中token获取到的password为:********{}",password);
        logger.info("********AuthenticationInfo中token获取到的username为:********{}",username);
        User byName = userService.findByName(username);
        // 3.查询用户是否存在，密码是否正确
        if(null != byName && byName.getPassword().equals(password)){
            // 4.密码正确返回安全数据
            // 安全数据  密码   realm域名
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(byName, byName.getPassword(), this.getName());
            return simpleAuthenticationInfo;

        }
        // 5.不一致返回null
        return null;
    }
}
